<?php
/**
 * @author Jumper Swordwave
 * date: 2021/04/20
 */
declare(strict_types=1);
namespace App\Game\Task;

use App\Game\Core\{Packet, Response, Command};
use App\Game\Service\UserService;
use App\Game\Model\{Room, User};

/**
 * 聊天任务
 */
class ChatTask
{
    /**
     * 广播聊天消息给同房间用户
     * @param Room  $room   房间
     * @param User  $user   发言人
     * @param string    $content 内容
     */
    public function broadcast(Room $room, User $user, string $content)
    {
        $srv = server();
        $res = Response::success(Command::CHAT_MSG_RES, [
            'user' => $user->toArray(),
            'content' => $content,
        ]);
        $userService = container()->get(UserService::class);
        $users = $userService->findUsers($room->users);

        foreach($users as $_user) {
            if ($_user->id == $user->id) continue;    //不给自己发送
            $srv->push($_user->fd, Packet::encode($res->getResult()), WEBSOCKET_OPCODE_BINARY);
        }
    }
}